use diesel::prelude::*;

use crate::{database::schema, route};

#[derive(Queryable, Selectable)]
#[diesel(table_name = schema::post)]
#[diesel(check_for_backend(diesel::mysql::Mysql))]
pub struct Post {
    pub id: i32,
    pub title: String,
    pub cover: String,
    pub tid: i32,
    pub sid: String,
    pub tids: String,
}

#[derive(Insertable, AsChangeset)]
#[diesel(table_name = schema::post)]
pub struct NewPost<'a> {
    pub title: &'a str,
    pub cover: &'a str,
    pub tid: i32,
    pub sid: &'a str,
    pub tids: String,
}

impl<'a> From<&'a route::form::post::NewPostForm> for NewPost<'a> {
    fn from(post: &'a route::form::post::NewPostForm) -> Self {
        NewPost {
            title: &post.title,
            cover: &post.cover,
            tid: post.tid,
            sid: &post.sid,
            tids: post
                .tids
                .iter()
                .map(|tid| tid.to_string())
                .collect::<Vec<String>>()
                .join(","),
        }
    }
}

impl<'a> From<&'a Post> for NewPost<'a> {
    fn from(post: &'a Post) -> Self {
        NewPost {
            title: &post.title,
            cover: &post.cover,
            tid: post.tid,
            sid: &post.sid,
            tids: post.tids.to_string(),
        }
    }
}
